package com.work.yshop.ui.activity;

import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.work.yshop.R;
import com.work.yshop.model.Article;

/**
 * 文章详情页面
 */
public class ArticleDetailActivity extends AppCompatActivity {

    private static final String TAG = "ArticleDetailActivity";
    
    private ImageView ivCover;
    private TextView tvTitle;
    private TextView tvAuthor;
    private TextView tvPublishDate;
    private TextView tvViewCount;
    private TextView tvContent;
    private ProgressBar progressBar;
    private ImageView btnBack;
    private ImageView btnShare;
    private LinearLayout btnLike;
    private LinearLayout btnCollect;
    private LinearLayout btnComment;
    
    private int articleId;
    private Article currentArticle;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_article_detail);
        
        // 获取文章ID
        articleId = getIntent().getIntExtra("article_id", -1);
        if (articleId == -1) {
            Toast.makeText(this, "文章不存在", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }
        
        initViews();
        setupListeners();
        
        // 加载文章
        loadArticle();
    }
    
    private void initViews() {
        ivCover = findViewById(R.id.iv_cover);
        tvTitle = findViewById(R.id.tv_title);
        tvAuthor = findViewById(R.id.tv_author);
        tvPublishDate = findViewById(R.id.tv_publish_date);
        tvViewCount = findViewById(R.id.tv_view_count);
        tvContent = findViewById(R.id.tv_content);
        progressBar = findViewById(R.id.progress_bar);
        btnBack = findViewById(R.id.btn_back);
        btnShare = findViewById(R.id.btn_share);
        btnLike = findViewById(R.id.btn_like);
        btnCollect = findViewById(R.id.btn_collect);
        btnComment = findViewById(R.id.btn_comment);
    }
    
    private void setupListeners() {
        btnBack.setOnClickListener(v -> onBackPressed());
        
        btnShare.setOnClickListener(v -> {
            if (currentArticle != null) {
                // 分享文章
                Intent shareIntent = new Intent(Intent.ACTION_SEND);
                shareIntent.setType("text/plain");
                shareIntent.putExtra(Intent.EXTRA_SUBJECT, currentArticle.getTitle());
                shareIntent.putExtra(Intent.EXTRA_TEXT, 
                        currentArticle.getTitle() + "\n\n" + 
                        currentArticle.getSummary() + "\n\n" + 
                        "来自益农APP");
                startActivity(Intent.createChooser(shareIntent, "分享文章"));
            }
        });
        
        btnLike.setOnClickListener(v -> {
            Toast.makeText(this, "点赞成功", Toast.LENGTH_SHORT).show();
        });
        
        btnCollect.setOnClickListener(v -> {
            Toast.makeText(this, "收藏成功", Toast.LENGTH_SHORT).show();
        });
        
        btnComment.setOnClickListener(v -> {
            Toast.makeText(this, "评论功能即将上线", Toast.LENGTH_SHORT).show();
        });
    }
    
    private void loadArticle() {
        // 显示加载中
        progressBar.setVisibility(View.VISIBLE);
        
        // 从数据库加载文章数据
        new Thread(() -> {
            Article article = getArticleFromDatabase(articleId);
            
            // 在UI线程更新界面
            runOnUiThread(() -> {
                // 隐藏加载中
                progressBar.setVisibility(View.GONE);
                
                if (article != null) {
                    currentArticle = article;
                    displayArticle(article);
                    
                    // 更新文章阅读量
                    updateArticleViewCount(articleId, article.getViewCount() + 1);
                } else {
                    // 显示错误信息
                    Toast.makeText(this, "文章不存在或已被删除", Toast.LENGTH_SHORT).show();
                    finish();
                }
            });
        }).start();
    }
    
    /**
     * 从数据库获取文章
     */
    private Article getArticleFromDatabase(int articleId) {
        ContentResolver resolver = getContentResolver();
        Uri articleUri = Uri.withAppendedPath(ArticleProvider.CONTENT_URI, String.valueOf(articleId));
        
        try {
            Cursor cursor = resolver.query(articleUri, null, null, null, null);
            
            if (cursor != null && cursor.moveToFirst()) {
                // 从Cursor中提取文章数据
                int idIndex = cursor.getColumnIndex("_id");
                int titleIndex = cursor.getColumnIndex("title");
                int summaryIndex = cursor.getColumnIndex("summary");
                int contentIndex = cursor.getColumnIndex("content");
                int imageUrlIndex = cursor.getColumnIndex("image_url");
                int publishDateIndex = cursor.getColumnIndex("publish_date");
                int viewCountIndex = cursor.getColumnIndex("view_count");
                int categoryIndex = cursor.getColumnIndex("category");
                
                int id = idIndex != -1 ? cursor.getInt(idIndex) : 0;
                String title = titleIndex != -1 ? cursor.getString(titleIndex) : "";
                String summary = summaryIndex != -1 ? cursor.getString(summaryIndex) : "";
                String content = contentIndex != -1 ? cursor.getString(contentIndex) : "";
                String imageUrl = imageUrlIndex != -1 ? cursor.getString(imageUrlIndex) : "";
                String publishDate = publishDateIndex != -1 ? cursor.getString(publishDateIndex) : "";
                int viewCount = viewCountIndex != -1 ? cursor.getInt(viewCountIndex) : 0;
                String category = categoryIndex != -1 ? cursor.getString(categoryIndex) : "";
                
                cursor.close();
                
                // 创建文章对象
                return new Article(id, title, summary, content, imageUrl, publishDate, viewCount, category);
            }
            
            if (cursor != null) {
                cursor.close();
            }
        } catch (Exception e) {
            Log.e(TAG, "加载文章失败: " + e.getMessage(), e);
        }
        
        return null;
    }
    
    /**
     * 更新文章阅读量
     */
    private void updateArticleViewCount(int articleId, int newViewCount) {
        new Thread(() -> {
            ContentResolver resolver = getContentResolver();
            Uri articleUri = Uri.withAppendedPath(ArticleProvider.CONTENT_URI, String.valueOf(articleId));
            
            android.content.ContentValues values = new android.content.ContentValues();
            values.put("view_count", newViewCount);
            
            try {
                resolver.update(articleUri, values, null, null);
            } catch (Exception e) {
                Log.e(TAG, "更新阅读量失败: " + e.getMessage(), e);
            }
        }).start();
    }
    
    private void displayArticle(Article article) {
        // 设置标题
        tvTitle.setText(article.getTitle());
        
        // 设置作者 - 使用分类代替作者
        tvAuthor.setText("分类: " + article.getCategory());
        
        // 设置发布日期
        tvPublishDate.setText("发布时间: " + article.getPublishDate());
        
        // 设置阅读量
        tvViewCount.setText("阅读量: " + article.getViewCount());
        
        // 设置内容 - 支持HTML格式
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
            tvContent.setText(Html.fromHtml(article.getContent(), Html.FROM_HTML_MODE_COMPACT));
        } else {
            tvContent.setText(Html.fromHtml(article.getContent()));
        }
        
        // 加载封面图片
        if (article.getImageUrl() != null && !article.getImageUrl().isEmpty()) {
            ImageLoader.loadImage(this, article.getImageUrl(), ivCover);
        }
    }
    
    /**
     * 启动文章详情页
     */
    public static void start(Context context, int articleId) {
        Intent intent = new Intent(context, ArticleDetailActivity.class);
        intent.putExtra("article_id", articleId);
        context.startActivity(intent);
    }
} 